<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/10/29
 * Time: 19:22
 */

namespace app\pipeline\admin;


use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\company\model\Company as CompanyModel;
use app\pipeline\model\Pipe as PipeModel;
use app\pipeline\model\Business as BusinessModel;
use app\pipeline\model\Equipment as EquipmentModel;


class Pipe extends Admin
{

    public function index(){
        $map=$this->getMap();
        if($this->user_auth['role']!==1&&$this->user_auth['company_id']!==0){
            if($this->user_auth['company_type']=='third'){
                $company_ids=CompanyModel::where('b_company',$this->user_auth['company_id'])->column('id');
                $map[]=['company_id','in',$company_ids];
            }else{
                $map[]=['company_id','=',$this->user_auth['company_id']];
            }

        }

        $data_list = PipeModel::where($map)->order('id','desc')->paginate()->each(function($value){
            if($value['company_id']){
                $value['company_id']=CompanyModel::where('id',$value['company_id'])->value('name');
            }
        });
        $zbuilder=ZBuilder::make('table')
            ->setPageTitle('设备管理') // 页面标题
            ->setTableName('equipment') // 设置表名
            ->setSearch(['name' => '设备名称', 'id' => 'ID','number'=>'设备编号']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['id', 'ID'],
                ['name', '管道名称'],
                ['number', '编号'],
                ['level', '级别'],
                ['specifications', '规格'],
                ['surface', '表面状况'],
                ['material', '管道材质'],
                ['company_id', '所属公司'],
                ['longitude', '管道经度'],
                ['latitude', '管道纬度'],
                ['address', '地址'],
                ['create_time', '创建时间'],
                ['update_time', '修改时间'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButtons(
                [
                    'edit'=> ['title'=>'编辑','href' => url('pipe_save', ['id' => '__id__'])],
                    'delete'=>['title'=>'删除','href'=>url('pipe_del',['id'=>'__id__'])]
                ]
            );
        //无设备公司角色不能额添加管道
        if($this->user_auth['company_type']!='third_slave'){
            $zbuilder->addTopButton('add',['href'=>url('pipe_save')]);
        }
        return $zbuilder->setRowList($data_list) // 设置表格数据
                        ->fetch(); // 渲染模板

    }

    public function pipe_save(){
        if($this->user_auth['company_type']=='third_slave'){
            $this->error('无权添加管道信息');
        }
        if($this->request->isPost()){
            $data=$this->request->post();
            if($this->user_auth['role']!==1&&$this->user_auth['company_type']=='pipemanage'){
                $data['company_id']=$this->user_auth['company_id'];
            }
            // 验证
            $result = $this->validate($data, 'Pipe');
            if(true !== $result) $this->error($result);
            if(!empty($data['id'])){
                $result=PipeModel::update($data);
                action_log('piep_edit','pipe',$data['id'],UID,json_encode($data,JSON_UNESCAPED_UNICODE));
            }else{
                $result=PipeModel::create($data);
                action_log('piep_add','pipe',$data['id'],UID,$data['name']);
            }
            if(!$result){
                $this->error('编辑失败');
            }
            $this->success('编辑成功','index');
        }

        $id=$this->request->param('id');
        $info=PipeModel::get($id);
        // 显示编辑页面
        $zbuilder = ZBuilder::make('form')
            ->setPageTitle('编辑管道信息')
            ->setPageTips('请谨慎操作', 'warning');
        if ($this->user_auth['role'] == 1) {
            $company_list = CompanyModel::where('company_type','neq','third')->column('name', 'id');
            $zbuilder->addFormItem('select', 'company_id', '管道所属公司', '<span class="text-danger">必填</span>', $company_list);
        }elseif($this->user_auth['company_type']=='third'){
            $company_list = CompanyModel::whereRaw("b_company = {$this->user_auth['company_id']}")
                ->column('name', 'id');
            if(empty($company_list)){
                $this->error('请先添加委托公司');
            }
            $zbuilder->addFormItem('select', 'company_id', '委托公司', '<span class="text-danger">必填</span>', $company_list);
        }
        return $zbuilder->addFormItems([
            ['hidden', 'id'],
            ['text', 'name', '管道名称', '<span class="text-danger">必填</span>'],
            ['text', 'number', '管道编号', '<span class="text-danger">必填</span>'],
            ['text', 'level', '管道级别'],
            ['text', 'specifications', '管道规格'],
            ['text', 'surface', '表面状况'],
            ['text', 'material', '管道材质'],
            ['text', 'longitude', '管道经度'],
            ['text', 'latitude', '管道纬度'],
            ['text', 'address', '地址'],
            ['text', 'other', '设备参数等(待补充)']
        ])->setFormData($info)->fetch();

    }

    public function pipe_del(){
        $id=$this->request->param('id');
        $has_pipe=PipeModel::where("id",$id)->find();
        if(!$has_pipe){
            $this->error('未找到管道信息');
        }
        $has_business=BusinessModel::whereRaw("find_in_set($id,pipeline_number)")->count(1);
        if($has_business){
            $this->error('当前管道已有业务检测中,无法删除');
        }
        $del_result=PipeModel::where("id",$id)->delete();
        if(!$del_result){
            $this->error('删除失败');
        }
        action_log('pipe_del','pipe',$id,UID,json_encode($has_pipe,JSON_UNESCAPED_UNICODE));
        $this->success('删除成功');
    }

}